/*---------------------------------------------------------------------------
*		copyright @2007,all right reserved by lyb@ax
*
*		FILE NAME	:	dblog.c
*		AUTHOR		:	LYB@AX
*		DATE		:	2007/04/05
*		PURPOSE		:	dblog.c
*
*		leiyuanbing@163.com,axlybx@gmail.com
*----------------------------------------------------------------------------*/

#include "dblog.h"
#include "os.h"

#include <stdio.h>
#include <string.h>
#include <assert.h>

#ifdef WIN32
 #define vsnprintf _vsnprintf
#endif

#ifndef LOG_FILE
#define LOG_FILE			"futrue.log\0"
#define MAX_LOG_FILE_SIZE   (1024* 1024*10)
#endif

//##ModelId=4755751001D8



//##ModelId=4755751001D4
BaseLog::BaseLog()
{	
	m_pSem   = OS_SemCreate(1);
	m_pf = fopen(LOG_FILE,"w+");
	if(m_pf == NULL)
		return;

   	rewind(m_pf);

	fseek(m_pf,0,SEEK_END);

	unsigned int nSize = ftell(m_pf);

	rewind(m_pf);

	if( nSize >= MAX_LOG_FILE_SIZE)
	{
		fclose(m_pf);
		m_pf = fopen(LOG_FILE,"wt");
	}
}

//##ModelId=4755751001C7
BaseLog::~BaseLog()
{
	OS_SemSignal(m_pSem);
	OS_SemDestroy(m_pSem);
	m_pSem = 0;
	if(m_pf)
	fclose(m_pf);
	m_pf = 0;
}

//##ModelId=4755751001C5
BaseLog&	BaseLog::getInstance()
{
	static BaseLog theLog;

	return theLog;
	
}

#define MAX_MSG_SIZE (1024)
//##ModelId=4755751001F5
void	BaseLog::error(ELevel eLevel,char* fmt,...)
{
	va_list ap;
	int	ret = 0;
	char	szMsg[MAX_MSG_SIZE];

    	assert( fmt );

	OS_SemWait(m_pSem,SEM_WAIT_INFINITE);

	va_start( ap, fmt );
	ret = vsnprintf(szMsg , MAX_MSG_SIZE -1, fmt, ap );
	va_end( ap );

	if(ret < 0)
	{
		assert(0);
	}
	else
	{
		szMsg[ret] = 0;
		//m_cStream<<"\n Level "<<eLevel<<szMsg<<endl;
		#ifdef AX_DEBUG
		fprintf(stderr,szMsg);
		#endif

		if(m_pf)
		{
		  fwrite(szMsg,1,ret,m_pf);
		  fflush(m_pf);
		}
	}

	OS_SemSignal(m_pSem);
}

//##ModelId=475575100214
void   BaseLog:: error(char* fmt,...)
{
	va_list ap;
	int	ret = 0;
	char	szMsg[MAX_MSG_SIZE];

    	

	OS_SemWait(m_pSem,SEM_WAIT_INFINITE);

	va_start( ap, fmt );
	ret = vsnprintf(szMsg , MAX_MSG_SIZE -1, fmt, ap );
	va_end( ap );

	if(ret < 0)
	{
		assert(0);
	}
	else
	{
		szMsg[ret] = 0;
		#ifdef AX_DEBUG
		fprintf(stderr,szMsg);
		#endif

		if(m_pf)
		{
			fwrite(szMsg,1,ret,m_pf);
			fflush(m_pf);
		}
	}
	OS_SemSignal(m_pSem);
}

void   BaseLog:: events(char* fmt,...)
{
	va_list ap;
	int	ret = 0;
	char	szMsg[MAX_MSG_SIZE];



	OS_SemWait(m_pSem,SEM_WAIT_INFINITE);

	va_start( ap, fmt );
	ret = vsnprintf(szMsg , MAX_MSG_SIZE -1, fmt, ap );
	va_end( ap );

	if(ret < 0)
	{
		assert(0);
	}
	else
	{
		szMsg[ret] = 0;
#ifdef AX_DEBUG
		fprintf(stderr,szMsg);
#endif

		if(m_pf)
		{
		    //	fwrite("EVENT:", 1, strlen("EVENT:"), m_pf);
			fwrite(szMsg,1,ret,m_pf);
			fflush(m_pf);
		}
		//m_cStream<<"\n NO SET "<<LOG_WARN<<szMsg<<endl;
	}
	OS_SemSignal(m_pSem);
}


